package com.xdwanj.service.impl;

import com.xdwanj.dao.OrderDao;
import com.xdwanj.dao.ShoppingCartDao;
import com.xdwanj.dao.impl.OrderDaoImpl;
import com.xdwanj.dao.impl.ShoppingCartDaoImpl;
import com.xdwanj.pojo.ShoppingCart;
import com.xdwanj.service.ShoppingCartService;
import com.xdwanj.util.PageBean;

import java.util.ArrayList;
import java.util.List;

public class ShoppingCartServiceImpl implements ShoppingCartService {
    ShoppingCartDao shoppingCartDao = new ShoppingCartDaoImpl();

    @Override
    public PageBean<ShoppingCart> findShoppingCartList(String queryName, int userId, int currentPageNo, int pageSize) {
        PageBean customerPageDto = null;
        try {
            customerPageDto = shoppingCartDao.findShoppingCartByUser(queryName, userId, currentPageNo, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return customerPageDto;
    }

    @Override
    public boolean conversion(int uid, int scid) {
        OrderDao orderDao = new OrderDaoImpl();
        ShoppingCart shoppingCart = null;
        boolean flag = false;
        try {
            shoppingCart = shoppingCartDao.findById(scid);
            orderDao.ConversionOrderByCommodity(uid, shoppingCart.getCommodityId(), shoppingCart.getCommodityNum());
            shoppingCartDao.deleteShoppingCart(scid, uid);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public boolean delete(int scid, int uid) {
        boolean flag = false;
        try {
            shoppingCartDao.deleteShoppingCart(scid, uid);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public boolean add(int uid, int coid, int count) {
        boolean flag = false;
        try {
            List<ShoppingCart> shoppingCarts = shoppingCartDao.findByUserId(uid);
            System.out.println(shoppingCarts);
            List<Integer> commodities = new ArrayList<>();
            for (ShoppingCart shoppingCart : shoppingCarts) {
                commodities.add(shoppingCart.getCommodityId());
            }

            if (commodities.contains(coid)) {
                shoppingCartDao.updateShoppingCart(uid, coid, count);
            } else {
                shoppingCartDao.addShoppingCart(uid, coid, count);
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}
